package com.ce.framework.struts2.config;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterConfig;

import org.apache.struts2.config.StrutsXmlConfigurationProvider;

import com.ce.framework.struts2.filter.CsmisStruts2PrepareFilter;
import com.ce.framework.util.LogUtil;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.util.location.LocatableProperties;

public class CsmisStruts2XmlConfiguration implements ConfigurationProvider {
	
	public static final String FILTER_CONFIG_FILE_PARAM_NAME = "csmisStruts2Config";
	
	private List<StrutsXmlConfigurationProvider> provs;

	public CsmisStruts2XmlConfiguration() {
		//使用filterConfig中的配置进行解析
		FilterConfig conf = CsmisStruts2PrepareFilter.config;
		provs = new ArrayList<StrutsXmlConfigurationProvider>();
		if(conf!=null){
			String config = conf.getInitParameter(FILTER_CONFIG_FILE_PARAM_NAME);
	        if (config != null) {
	            String[] files = config.split("\\s*[,]\\s*");
	            File baseDir = new File(conf.getServletContext().getRealPath("/"));
	            for (String file : files) {
	                File f = new File(baseDir,file);
	                if(f.exists()){
	                	provs.add(new StrutsXmlConfigurationProvider(f.getAbsolutePath(),false,conf.getServletContext()));
	                }
	                else{
	                	LogUtil.logWarn("文件["+f.getAbsolutePath()+"]不存在！");
	                }
	            }
	        }
		}
	}

	public void destroy() {
		for(int i=0;i<provs.size();i++){
			provs.get(i).destroy();
		}
	}

	public void init(Configuration configuration) throws ConfigurationException {
		for(int i=0;i<provs.size();i++){
			provs.get(i).init(configuration);
		}
	}

	public boolean needsReload() {
		return false;
	}

	public void register(ContainerBuilder containerbuilder, LocatableProperties locatableproperties) throws ConfigurationException {
		for(int i=0;i<provs.size();i++){
			provs.get(i).register(containerbuilder,locatableproperties);
		}
	}

	public void loadPackages() throws ConfigurationException {
		for(int i=0;i<provs.size();i++){
			provs.get(i).loadPackages();
		}
	}

}
